#!/bin/bash

PERLLIBS="test-mockmodule test-mockobject test-differences test-file test-mocktime test-tester test-cmd test-output test-class log-log4perl devel-stacktrace gd-gd2 config-tiny params-validate perl6-junction file-slurp readonly mail-rfc822-address io-interface data-validate-domain clone-fast html-mason proc-processtable test-deep dbi json json-xs yaml-libyaml redis linux-inotify2 sys-cpuload filesys-df authen-simple-pam nmap-parser dir-self file-readbackwards chart date-calc test-net-ldap soap-lite string-shellquote trycatch-lite string-random text-dhcpleases class-singleton xml-libxml plack test-sharedfork"

ADDITIONAL_ARGS=""
EXTRA_ARGS="-j4"
MODULES_WITH_TESTS="common core samba firewall antivirus mail mailfilter"

while getopts ":vjscf" opt; do
    case $opt in
    v)
        VERBOSE="yes"
        ADDITIONAL_ARGS="-v"
        shift $((OPTIND-1))
        ;;
    j)
        JUNIT="yes"
        shift $((OPTIND-1))
        ;;
    s)
        #We execute the tests in a single job without parallelization
        EXTRA_ARGS=""
        shift $((OPTIND-1))
        ;;
    c)
        COVERAGE="yes"
        shift $((OPTIND-1))
        ;;
    f)
        FAST="yes"
        shift $((OPTIND-1))
        ;;
    esac
done

MISSINGLIBS=""

if [ "$FAST" != "yes" ]; then
    # TODO: Improve this
    for i in $PERLLIBS
    do
        pkg="lib$i-perl"
        if ! dpkg -s $pkg >/dev/null 2>&1
        then
            MISSINGLIBS="$MISSINGLIBS $pkg"
        fi
    done
fi

if [ -n "$MISSINGLIBS" ]
then
    if [ "$JUNIT" != "yes" ]
    then
        echo -e "The following packages are not installed:\n $MISSINGLIBS"
        echo -e "Installing them..."
    fi
    export DEBIAN_FRONTEND=noninteractive
    sudo -E apt-get install -y --force-yes --no-install-recommends $MISSINGLIBS >/dev/null 2>&1
fi

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $SCRIPT_DIR/../../main

INCLUDES=$(find . -name src|sed 's/.\//-I /'|xargs)

# Create the modules directory
CONF_DIR=${ZENTYAL_MODULES_SCHEMAS:=/tmp/zentyal-test-schemas/}
sudo rm -f $CONF_DIR/*
sudo rm -r $CONF_DIR
export ZENTYAL_MODULES_SCHEMAS

#Temporary fix to permissions problems with this folder
sudo chmod 777 /var/lib/zentyal/tmp

test -d $CONF_DIR || mkdir $CONF_DIR
find . -wholename '*schemas/*.yaml' -exec cp {} $CONF_DIR \;

COMMON_ARGS="$EXTRA_ARGS -r --timer"

if [ "$@" == "ALL" ]
then
    MODULES=$MODULES_WITH_TESTS
else
    MODULES=$@
fi

if [ "$COVERAGE" == "yes" ]
then
    export HARNESS_PERL_SWITCHES="-MDevel::Cover=+ignore,\.t,\TestStub.pm,\Test.pm\$"
fi

if [ "$JUNIT" == "yes" ]
then
    PROVE="prove $COMMON_ARGS --formatter=TAP::Formatter::JUnit $INCLUDES $MODULES"
else
    PROVE="prove $COMMON_ARGS $ADDITIONAL_ARGS $INCLUDES $MODULES"
fi

if [ "$VERBOSE" == "yes" ]
then
    LANGUAGE=C $PROVE
else
    LANGUAGE=C $PROVE 2>/dev/null
fi
